package model;

import model.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Creared with IntelliJ IDEA.
 * Description:这个类用于封装用户表的基本操作(增删改查)
 * User:yxd
 * Date:2022-06-04
 * Time:17:10
 */
public class UserDao {
    //需要实现的操作:像这里的注册和删除用户信息就不写了(在页面里面也没有显示)
    //1.根据用户名来查找用户信息(主要是登录的时候会用到)
    public User selectByName(String username){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            //sql语句
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);
            //执行sql语句
            resultSet = statement.executeQuery();
            //遍历结果 由于这里不能重复,因此也是使用if而不是while
            if(resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
    //2.根据用户id来查找用户信息(主要是博客详情页,就可以根据用户id来查找作者的名字,并把作者的信息显示出来
    public User selectById(int userId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        try {
            connection = DBUtil.getConnection();
            //sql语句
            String sql = "select * from user where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            //执行sql语句
            resultSet = statement.executeQuery();
            //遍历结果 由于这里是主键,因此也是使用if而不是while
            if(resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
}
